require(["jquery", "bbcare", "echarts", "migrate_jqprint", 'jqprint',
    "scprit/department/view/template/follow-up/common.js"
], function($, $bb, echarts, migrate, $print, $common) {

    var URL = $bb.baseUrl("followapp");
    var obj = $bb.getPageParams();
    var userId = obj.babyId || obj.userId;
    type = 'Gesell'
    if (obj.doctorName && obj.createTime) {
        $("#checkTime").html(obj.createTime);
        $("#checkName").html(obj.doctorName);
    } else {
        var account = eval('(' + sessionStorage.account + ')');
        var accountName = account.alias;
        $("#checkTime").html($common.getNowFormatDate());
        $("#checkName").html(accountName);
    }
    'use strict';
    var result, answerId, answerResult;
    var suggestHtml = '';
    result = JSON.parse(localStorage.getItem("GesellIntelligence"));
    // $("#da").html("<p>DA</p><i style='font-size:20px;'>"+(result.DA).toFixed(1)+"</i>");
    // $("#ca").html("<p>CA</p><i style='font-size:20px;'>"+(result.CA).toFixed(1)+"</i>");
    // $("#dq").html("<p>DQ</p><i style='font-size:20px;'>"+(result.DQ).toFixed(1)+"</i>");
    $(".adaptabilityDa").html(parseFloat(result.adaptabilityDa).toFixed(1));
    $(".adaptabilityDq").html(parseFloat(result.adaptabilityDq).toFixed(1) + '%');
    $(".adaptabilityLevel").html(result.adaptabilityLevel);

    $(".sportsDa").html(parseFloat(result.sportsDa).toFixed(1));
    $(".sportsDq").html(parseFloat(result.sportsDq).toFixed(1) + '%');
    $(".sportsLevel").html(result.sportsLevel);

    $(".fineActionDa").html(parseFloat(result.fineActionDa).toFixed(1));
    $(".fineActionDq").html(parseFloat(result.fineActionDq).toFixed(1) + '%');
    $(".fineActionLevel").html(result.fineActionLevel);

    $(".languageDa").html(parseFloat(result.languageDa).toFixed(1));
    $(".languageDq").html(parseFloat(result.languageDq).toFixed(1) + '%');
    $(".languageLevel").html(result.languageLevel);

    $(".personalDa").html(parseFloat(result.personalDa).toFixed(1));
    $(".personalDq").html(parseFloat(result.personalDq).toFixed(1) + '%');
    $(".personalLevel").html(result.personalLevel);

    if ($(".mainCenter").parents(".assess-wrap").length > 0) {
        $(".mainCenterRightT").hide();
    }
    getHistoryScore();
    $(".mask, .AddInformation").hide();
    $(".AddInformation h4 span").click(function(event) {
        $(".mask, .AddInformation").hide();
    });
    $("#printInfo").click(function(event) {
        $("#resultInfo").jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true //表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
    });
    $("#checkOrigin").click(function() {
        var result = answerResult;
        $.extend(obj, { 'result': result });
        $bb.openPage("gesellDetail", obj);
    })

    function showEcharts(data) {
        var xdata = [];
        var yAdaptability = { name: '', type: 'line', smooth: true, data: [] };
        var ysports = { name: '', type: 'line', smooth: true, data: [] };
        var yfineAction = { name: '', type: 'line', smooth: true, data: [] };
        var ylanguage = { name: '', type: 'line', smooth: true, data: [] };
        var ypersonal = { name: '', type: 'line', smooth: true, data: [] };

        for (var i = 0; i < data.length; i++) {
            // xdata.push(new Date(data[i].createTime).Format("yyyy-MM-dd"))
            xdata.push((data[i].createTime).split(' ')[0])
            yAdaptability.data.push(data[i].adaptabilityDq)
            ysports.data.push(data[i].sportsDq)
            yfineAction.data.push(data[i].fineActionDq)
            ylanguage.data.push(data[i].languageDq)
            ypersonal.data.push(data[i].personalDq)
        }
        yAdaptability.name = '适应性DQ'
        ysports.name = '大运动DQ'
        yfineAction.name = '精细运动DQ'
        ylanguage.name = '语言DQ'
        ypersonal.name = '个人-社交DQ'

        var myChart = echarts.init(document.getElementById('myChart'));
        myChart.setOption({
            title: {
                text: 'Gesell发育商发展趋势',
                left: "center"
            },
            tooltip: { trigger: 'axis' },
            calculable: true,
            legend: {
                top: "30px",
                data: ['适应性DQ', '大运动DQ', '精细运动DQ', '语言DQ', '个人-社交DQ']
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xdata
            },
            yAxis: {
                type: 'value'
            },
            series: [yAdaptability, ysports, yfineAction, ylanguage, ypersonal],
            animation: false
        })
        $("#gesellResultMyChart").html('<img src="' + myChart.getDataURL({ type: "png", backgroundColor: '#fff' }) + '" style="width: 100%;height:100%; "/>');
    }

    function getHistoryScore() {
        $bb.ajax({
            url: URL + "service/evaluation/recordlist", //baby地址
            data: JSON.stringify({
                data: {
                    "evaluationType": type,
                    "channelType": "2",
                    "queueUserId": userId,
                }
            }),
            success: function(data) {
                if (data.rows) {
                    showEcharts(data.rows);
                    answerId = data.rows[0].id;
                    answerResult = data.rows[0].result;
                    getBabyInfo();
                    getGuide();
                }
            },
            error: function(errorMsg) {
                alert("图表请求数据失败!");
            }
        })
    }

    function getGuide() {
        $bb.ajax({
            url: URL + "service/evaluation/getGuide",
            async: false,
            data: JSON.stringify({
                data: {
                    "examinationPaperName": type,
                    "channelType": '2',
                    "queueUserId": userId,
                    "evaluationId": answerId
                }
            }),
            success: function(data) {
                if (data.success) {
                    var arr = [];
                    for (var item in data.data) {
                        if (item != 'success') {
                            var obj = {};
                            obj.title = item;
                            obj.content = data.data[item];
                            arr.push(obj);
                        }
                    }
                    for (var i = 0; i < arr.length; i++) {
                        suggestHtml += '<div>' + arr[i].title + '</div>';
                        for (var j = 0; j < arr[i].content.length; j++) {
                            suggestHtml += '<div>' + arr[i].content[j].title + '</div><p>' + arr[i].content[j].describe[0] + '</p>'
                        }
                    }
                    $('#gesellSuggest').html(suggestHtml);
                    $("#gesellResultGuide").html('<h3 class="suggest_title">指导建议</h3>' + suggestHtml);
                }
            }
        })
    }

    function getBabyInfo() {
        $bb.ajax({
            url: URL + "service/evaluation/getEvaluationDetail",
            data: JSON.stringify({
                data: {
                    "evaluationType": type,
                    "channelType": "2",
                    "recordId": answerId,
                }
            }),
            success: function(data) {
                if (data.success) {
                    var babyInfo = data.data;
                    var gender = (babyInfo.gender == "M") ? "男" : "女";
                    var babyData = $common.babyInfoDeal(babyInfo);
                    $common.infoInit({ "id": "#babyInfoList", "data": babyData });
                    var reportTime = obj.createTime ? obj.createTime : $common.getNowFormatDate();
                    var date1 = new Date(reportTime); //开始时间
                    var date2 = new Date(babyInfo.birthday); //结束时间
                    var date3 = date1.getTime() - date2.getTime(); //时间差的毫秒数
                    //计算出相差天数
                    var day = Math.floor(date3 / (24 * 3600 * 1000));
                    //计算相差的年数
                    var age2 = $common.yearDayWeek(day, babyInfo.pregnancyDay);
                    var years = age2.year;
                    var weeks = age2.week;
                    var days = age2.day;
                    var babyInfo2 = '<li class="important"><a>姓名</a><br/><span>' + babyInfo.userName + '</span></li>' +
                        '<li class="important"><a>性别</a><br/><span>' + gender + '</span></li>' +
                        '<li class="important"><a>出生日期</a><br/><span>' + babyInfo.birthday + '</span></li>' +
                        '<li class="important"><a>月龄（岁）</a><br/><span>' + years + '</span></li>' +
                        '<li class="important"><a>月龄（周）</a><br/><span>' + weeks + '</span></li>' +
                        '<li class="important"><a>月龄（天）</a><br/><span>' + days + '</span></li>';
                    $("#babyInfo").html(babyInfo2);
                    // var gesellResult = "<ul><li><h3>发育周龄:" + (result.DA).toFixed(1) + "</h3></li><li><h3>实际周龄:" + (result.CA).toFixed(1) + "</h3></li>" +
                    //     "<li><h3>总发育商:" + (result.DQ).toFixed(1) + "</h3></li></ul>";
                    var gesellResult = '<h4 class="suggest_title">评价结果</h4><Table class="table"><tr><td></td><td>发育周龄 DA</td><td>发育商 DQ</td><td></td></tr><tr><td>适应性</td><td class="adaptabilityDa">' + parseFloat(result.adaptabilityDa).toFixed(1) +
                        '</td><td class="adaptabilityDq">' + parseFloat(result.adaptabilityDq).toFixed(1) + '%' + '</td><td class="adaptabilityLevel">' + result.adaptabilityLevel + '</td></tr><tr><td>大运动</td><td class="sportsDa">' +
                        parseFloat(result.sportsDa).toFixed(1) + '</td><td class="sportsDq">' + parseFloat(result.sportsDq).toFixed(1) + '%' + '</td><td class="sportsLevel">' + result.sportsLevel + '</td></tr><tr><td>精细运动</td>' +
                        '<td class="fineActionDa">' + parseFloat(result.fineActionDa).toFixed(1) + '</td><td class="fineActionDq">' + parseFloat(result.fineActionDq).toFixed(1) + '%' + '</td><td class="fineActionLevel">' + result.fineActionLevel +
                        '</td></tr><tr><td>语言</td><td class="languageDa">' + parseFloat(result.languageDa).toFixed(1) + '</td><td class="languageDq">' + parseFloat(result.languageDq).toFixed(1) + '%' + '</td><td class="languageLevel">' +
                        result.languageLevel + '</td></tr><tr><td>个人-社交</td><td class="personalDa">' + parseFloat(result.personalDa).toFixed(1) + '</td><td class="personalDq">' + parseFloat(result.personalDq).toFixed(1) + '%' +
                        '</td><td class="personalLevel">' + result.personalLevel + '</td></tr></Table>';
                    $("#gesellResult").html(gesellResult);
                }
            }
        });
    }


});